package com.app.couponsharelife.ui.main.home.search

import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.PDDGoodsListBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.ui.adapter.GoodsSearchAdapter
import com.app.couponsharelife.utils.DataUtils
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_searchpdd.*

/**
 *Created by xct on 2019/1/9
 *Description:
 */
class SearchPDDFragment:LazyFragment(),View.OnClickListener {
    private var pageIndex=1
    private var sortType="0"
    private var catId=""
    private var goodsList= arrayListOf<TaobaoGoodBean>()
    private var adapter: GoodsSearchAdapter?=null
    private var clickIndex=0
    private var isUp=false
    private var keyword=""
    companion object {
        fun newInstance(): SearchPDDFragment {
            val fragment = SearchPDDFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_searchpdd

    override fun initViews() {
        keyword=(activity as HomeSearchActivity).keyword
        setRefresh()
        adapter=GoodsSearchAdapter(activity!!,goodsList,"PDD")
        fragment_searchpdd_rv.layoutManager= GridLayoutManager(activity!!,2)
        fragment_searchpdd_rv.adapter=adapter
        fragment_searchpdd_zh.setOnClickListener(this)
        fragment_searchpdd_xl.setOnClickListener(this)
        fragment_searchpdd_textprice.setOnClickListener(this)
    }
    override fun onClick(v: View?) {
        when(v?.id){
            R.id.fragment_searchpdd_zh->{
                if (clickIndex!=0){
                    fragment_searchpdd_zh.setTextColor(ContextCompat.getColor(activity!!, R.color.act_main_bot_nav_select_text_color))
                    fragment_searchpdd_xl.setTextColor(ContextCompat.getColor(activity!!, R.color.black))
                    fragment_searchpdd_textprice.setTextColor(ContextCompat.getColor(activity!!, R.color.black))
                    pageIndex=1
                    sortType="0"
                    getGoodsList(false)
                }
                clickIndex=0
            }
            R.id.fragment_searchpdd_xl->{
                if (clickIndex!=1){
                    fragment_searchpdd_zh.setTextColor(ContextCompat.getColor(activity!!, R.color.black))
                    fragment_searchpdd_xl.setTextColor(ContextCompat.getColor(activity!!, R.color.act_main_bot_nav_select_text_color))
                    fragment_searchpdd_textprice.setTextColor(ContextCompat.getColor(activity!!, R.color.black))
                    pageIndex=1
                    sortType="6"
                    getGoodsList(false)
                }
                clickIndex=1
            }
            R.id.fragment_searchpdd_textprice->{
                if (clickIndex!=2) {
                    fragment_searchpdd_zh.setTextColor(ContextCompat.getColor(activity!!, R.color.black))
                    fragment_searchpdd_xl.setTextColor(ContextCompat.getColor(activity!!, R.color.black))
                    fragment_searchpdd_textprice.setTextColor(ContextCompat.getColor(activity!!, R.color.act_main_bot_nav_select_text_color))
                    pageIndex = 1
                    sortType = "3"
                    getGoodsList(false)
                }
                clickIndex = 2
            }
        }
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        fragment_searchpdd_smartrefresh.setOnMultiPurposeListener(object : OnMultiPurposeListener {
            override fun onFooterMoving(footer: RefreshFooter?, isDragging: Boolean, percent: Float, offset: Int, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderStartAnimator(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {

            }

            override fun onFooterReleased(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {

            }

            override fun onHeaderMoving(header: RefreshHeader?, isDragging: Boolean, percent: Float, offset: Int, headerHeight: Int, maxDragHeight: Int) {
                setAnima(percent)
            }

            override fun onFooterFinish(footer: RefreshFooter?, success: Boolean) {

            }

            override fun onFooterStartAnimator(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderReleased(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {
                animationDrawable.start()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                getGoodsList(false)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex=1
                getGoodsList(true)
            }

            override fun onHeaderFinish(header: RefreshHeader?, success: Boolean) {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    override fun lazyLoad() {
        getGoodsList(false)
    }
    fun refreshData(keywd:String){
        pageIndex=1
        keyword=keywd
        getGoodsList(false)
    }
    private fun getGoodsList(isRefresh:Boolean){
        if (!isRefresh&&pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map=HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["keyword"]= keyword
        map["sortType"]=sortType
        RetrofitWorker.retrofitWorker.getPDDGoodsList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map { DataUtils().pddData(it) }
                .subscribe(object : DisposableObserver<RemoteResultBean<PDDGoodsListBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<PDDGoodsListBean>) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (it.data!=null&&it.data!!.recordss!!.isNotEmpty()){
                            if (pageIndex==1){
                                goodsList.clear()
                                fragment_searchpdd_llerror.visibility= View.GONE
                                fragment_searchpdd_rv.visibility= View.VISIBLE
                                if (isRefresh){
                                    fragment_searchpdd_smartrefresh.finishRefresh()
                                }
                            }else{
                                fragment_searchpdd_smartrefresh.finishLoadMore()
                            }
                            goodsList.addAll(it.data!!.recordss!!)
                            if (it.data!!.recordss!!.size<10){
                                fragment_searchpdd_smartrefresh.finishLoadMoreWithNoMoreData()
                            }
                            pageIndex++
                            adapter!!.notifyDataSetChanged()
                        }else{
                            if (isRefresh){
                                fragment_searchpdd_smartrefresh.finishRefresh()
                            }
                            if (pageIndex==1&&goodsList.size==0){
                                fragment_searchpdd_smartrefresh.finishLoadMoreWithNoMoreData()
                                fragment_searchpdd_llerror.visibility= View.VISIBLE
                                fragment_searchpdd_rv.visibility= View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            fragment_searchpdd_smartrefresh.finishRefresh()
                        }
                        if (pageIndex>1){
                            fragment_searchpdd_smartrefresh.finishLoadMore()
                        }
                        if (pageIndex==1){
                            fragment_searchpdd_smartrefresh.finishLoadMoreWithNoMoreData()
                            fragment_searchpdd_llerror.visibility= View.VISIBLE
                            fragment_searchpdd_rv.visibility= View.GONE
                        }
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                            Log.e("eeee","----->"+e.toString())
                        }
                    }

                })
    }
}